//
//  LHMessage.m
//  LazyHome
//
//  Created by yh on 2018/4/17.
//  Copyright © 2018年 yh. All rights reserved.
//

#import "LHMessage.h"
#import "NSMutableData+BufferHandler.h"
#include "GBNumber.h"
@implementation LHMessage

+ (instancetype)messageWithData:(NSData *)data cmd:(ushort)cmd{
    NSMutableData *handleData = [NSMutableData dataWithData:data];
    [handleData readDataWithLength:5];
    LHMessage *message = [[LHMessage alloc] init];
    message.headData = [NSData dataWithBytes:&HEAR_DATA length:1];
    message.fnData = [NSData dataWithBytes:&fn length:1];
    message.cmdData = [NSData dataWithUshort:ushort_swap(cmd)];
    ushort len = data.length;
    len = ushort_swap(len);
    message.lengthData = [NSData dataWithBytes:&len length:2];
    message.data = data;
    return message;
}

- (NSData *)messageData{
    NSMutableData *handleData = [NSMutableData dataWithData:self.headData];
    [handleData appendData:self.fnData];
    [handleData appendData:self.cmdData];
    [handleData appendData:self.lengthData];
    [handleData appendData:self.data];
    return handleData;
}

- (ushort)swap:(ushort)value{
    return ((value & 0x00FF) << 8 ) | ((value & 0xFF00) >> 8);
}

@end
